package com.buercorp.wangyu.core1.ch12.threads.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列的使用
 * 抛出异常 特殊值 阻塞 超时
 * 插入
 * 移除
 * 检查
 * add remove element,  offer poll peek,  put take,  offer poll
 * 检查 element为空抛出异常  peek为空返回null 都返回队头元素
 * @author liyiyu
 */
public class QueueTest1 {
    public static void main(String[] args) throws InterruptedException {
        // 创建阻塞队列
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

        // 抛出异常
    /*    System.out.println(blockingQueue.add("aaa")); // true
        System.out.println(blockingQueue.add("bbb")); // true
        System.out.println(blockingQueue.add("ccc")); // true
        System.out.println(blockingQueue.add("aaa")); // 异常
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.element());*/


        // 特殊值
       /* System.out.println(blockingQueue.offer("aaa")); // true
        System.out.println(blockingQueue.offer("bbb")); // true
        System.out.println(blockingQueue.offer("ccc")); // true
//        System.out.println(blockingQueue.offer("aaa")); // false
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll()); // null
        System.out.println(blockingQueue.peek());*/


        // 阻塞
        /*blockingQueue.put("aaa"); //
        blockingQueue.put("bbb"); //
        blockingQueue.put("ccc"); //
//        blockingQueue.put("aaa"); // 阻塞

        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take(); // 阻塞*/


        // 超时
        System.out.println(blockingQueue.offer("aaa")); // true
        System.out.println(blockingQueue.offer("bbb")); // true
        System.out.println(blockingQueue.offer("ccc")); // true
//        System.out.println(blockingQueue.offer("aaa",3l, TimeUnit.SECONDS)); // 设置阻塞时间 false

        System.out.println(blockingQueue.poll()); // true
        System.out.println(blockingQueue.poll()); // true
        System.out.println(blockingQueue.poll()); // true
        System.out.println(blockingQueue.poll(3l,TimeUnit.SECONDS)); // 设置阻塞时间 null

    }
}
